package com.chinasoft.controller;

import com.chinasoft.dao.CommentDAO;
import com.chinasoft.dao.Impl.*;
import com.chinasoft.dao.SectionDAO;
import com.chinasoft.dao.UserDAO;
import com.chinasoft.entity.Comment;
import com.chinasoft.entity.Post;
import com.chinasoft.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by YE on 2018/5/25.
 */
@WebServlet(name = "CommentServlet", urlPatterns = {"/comment"})
public class CommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String comop=request.getParameter("comop");
        PostDAOImpl postDAO=new PostDAOImpl();
        UserDAO userDAO=new UserDAOImpl();
        SectionDAO sectionDAO=new SectionDAOImpl();
        CommentDAO commentDAO=new CommentDAOImpl();
        int length=10;
        Comment comment=null;
        Post post=null;
        List<Comment> commentList=null;
        if("getcomments".equals(comop)){
            int pid= Integer.parseInt(request.getParameter("pid"));
            int page=Integer.parseInt(request.getParameter("page"));
            int maxpage=commentDAO.getCommentCount(pid,length);
            try{
                post=postDAO.getPostsByPid(pid);
                commentList=commentDAO.getAllComments(pid,(page-1)*length,length);
                request.setAttribute("maxpage",maxpage);
                request.setAttribute("post",post);
                request.setAttribute("sname",sectionDAO.selectSection(post.getSid()).getSname());
                request.setAttribute("comments",commentList);
                request.setAttribute("count",commentDAO.getCount(pid));
                request.getRequestDispatcher("comment.jsp").forward(request,response);
            }catch (Exception e){
                response.sendRedirect("forum.jsp");
            }
        }else if("addcomment".equals(comop)){
            comment=new Comment();
            int pid=Integer.parseInt(request.getParameter("pid"));
            comment.setPid(pid);
            int uid=Integer.parseInt(request.getParameter("uid"));
            User user=userDAO.selectUser(uid);
            comment.setUser(user);
            comment.setCfloor(commentDAO.getCount(pid)+1);
            comment.setCcontent(request.getParameter("content"));
            comment.setCtime(request.getParameter("ctime"));
            out.print(commentDAO.addComment(comment));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
